package org.villacoapa.censo.web.servlet;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

public class UploadPhoto extends HttpServlet {
	
	private static Logger log = Logger.getLogger(UploadPhoto.class);

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		try {
			FileItemFactory factory = new DiskFileItemFactory();
			
			ServletFileUpload upload = new ServletFileUpload(factory);
			
			List items = upload.parseRequest(request);
			
			Iterator iter = items.iterator();
			
			while(iter.hasNext()){
				FileItem item = (FileItem)iter.next();
				if(!item.isFormField()){
					String fieldName = item.getFieldName();
					String fileName = item.getName();
					String contentType = item.getContentType();
					boolean isInMemory = item.isInMemory();
					long sizeInBytes = item.getSize();
					log.info("Field Name:"+fieldName+",File Name:"+fileName);
					log.info("Content Type:"+contentType+",Is In Memory:"+isInMemory+",Size:"+sizeInBytes);
					byte[] data = item.get();
					FileOutputStream fileOutSt = new FileOutputStream("c:\\Proyectos\\Censo\\FotosLoaded\\"+fileName);
					fileOutSt.write(data);
					fileOutSt.close();
				}
				
			}
		} catch (Exception e) {
			log.error("Se ha producido un error al tratar de leer el archivo", e.fillInStackTrace());
		}
		

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out
				.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the POST method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

}
